<template>
  <div class="template-selector">
    <!-- 顶部说明移除，根据需求隐藏 -->

    <div class="template-content">
      <!-- 项目选择 -->
      <div class="project-section">
        <h4>选择{{ sourceLabel }}项目</h4>
        <el-select
          v-model="selectedProjectId"
          placeholder="请选择项目"
          style="width: 100%"
          @change="handleProjectChange"
        >
          <el-option
            v-for="project in projects"
            :key="project._id"
            :label="`${project.name} (${project.protocolNumber})`"
            :value="project._id"
          >
            <span>{{ project.name }}</span>
            <span style="color: #8492a6; font-size: 12px; margin-left: 8px">
              v{{ project.version }} | {{ project.status }}
            </span>
          </el-option>
        </el-select>
      </div>

      <!-- 章节选择 -->
      <div v-if="selectedProjectId" class="sections-section">
        <h4>2. 选择章节</h4>
        <div class="section-list">
          <div v-if="loading" class="loading">加载中...</div>
          <div v-else-if="sections.length === 0" class="empty">该项目暂无章节</div>
          <div v-else>
            <div class="select-all-actions">
              <el-button 
                size="small" 
                @click="selectAllSections"
                :disabled="selectedSections.length === sections.length"
              >
                全选
              </el-button>
              <el-button 
                size="small" 
                @click="clearAllSections"
                :disabled="selectedSections.length === 0"
              >
                清除
              </el-button>
            </div>
            <el-checkbox-group v-model="selectedSections" class="section-checkbox-group" @change="updateTemplate">
              <div
                v-for="section in sections"
                :key="section._id"
                class="section-item"
              >
                <el-checkbox :value="section._id" class="section-checkbox">
                  <div class="section-info">
                    <div class="section-name">{{ section.name }}</div>
                    <div class="section-desc">{{ section.description || '无描述' }}</div>
                    <div class="section-stats">
                      表单数量: {{ section.forms?.length || 0 }}
                    </div>
                  </div>
                </el-checkbox>
                
                <!-- 表单选择 -->
                <div v-if="selectedSections.includes(section._id) && section.forms?.length > 0" class="forms-section">
                  <div class="forms-header">
                    <span>选择表单:</span>
                    <div class="form-actions">
                      <el-button 
                        size="small" 
                        text 
                        @click="selectAllForms(section._id)"
                        :disabled="getSelectedForms(section._id).length === section.forms.length"
                      >
                        全选
                      </el-button>
                      <el-button 
                        size="small" 
                        text 
                        @click="clearAllForms(section._id)"
                        :disabled="getSelectedForms(section._id).length === 0"
                      >
                        清除
                      </el-button>
                    </div>
                  </div>
                  <el-checkbox-group 
                    :model-value="getSelectedForms(section._id)"
                    @update:model-value="updateSelectedForms(section._id, $event)"
                    class="form-checkbox-group"
                  >
                    <el-checkbox
                      v-for="form in section.forms"
                      :key="form._id"
                      :value="form._id"
                      class="form-checkbox"
                    >
                      <div class="form-info">
                        <div class="form-name">{{ form.name }}</div>
                        <div class="form-code">{{ form._id || form.id }}</div>
                        <div class="form-stats">
                          字段数量: {{ form.config?.fields?.length || 0 }}
                        </div>
                      </div>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </el-checkbox-group>
          </div>
        </div>
      </div>

      <!-- 选择摘要 -->
      <div v-if="selectedSections.length > 0" class="selection-summary">
        <el-alert
          :title="`已选择 ${selectedSections.length} 个章节，${getTotalSelectedForms()} 个表单`"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { api } from '@/utils/api'

const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  filterIsTemplate: { type: Boolean, default: false },
  sourceLabel: { type: String, default: '模板' }
})

// 不使用全局 store 获取项目，避免影响项目管理页列表状态

const projects = ref([])
const sections = ref([])
const selectedProjectId = ref('')
const selectedSections = ref([])
const selectedForms = ref({}) // { sectionId: [formId1, formId2] }
const loading = ref(false)

// 获取项目列表
const getProjects = async () => {
  try {
    const resp = await api.projects.list({ isTemplate: props.filterIsTemplate, page: 1, limit: 1000, status: 'active' })
    // 只读本地数据，不写入全局 store，且再做一次兜底过滤
    const list = resp?.data || []
    projects.value = list.filter(p => (!!p.isTemplate) === props.filterIsTemplate)
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 项目选择变化
const handleProjectChange = async (projectId) => {
  selectedSections.value = []
  selectedForms.value = {}
  
  if (!projectId) {
    sections.value = []
    updateTemplate()
    return
  }

  try {
    loading.value = true
    // 获取项目的完整配置（包含章节和表单）
    const response = await api.projects.getConfig(projectId)
    sections.value = response.data.configSections || []
    
    // 如果没有configSections，尝试获取所有章节
    if (sections.value.length === 0) {
      const sectionsResponse = await api.sections.list(projectId)
      sections.value = sectionsResponse.data || []
      
      // 为每个章节获取表单
      for (const section of sections.value) {
        if (section.forms?.length > 0) {
          const formsWithConfig = []
          for (const form of section.forms) {
            try {
              const formResponse = await api.forms.getById(form._id)
              if (formResponse.success) {
                formsWithConfig.push(formResponse.data)
              }
            } catch (error) {
              console.warn('获取表单配置失败:', form.name, error)
              formsWithConfig.push(form)
            }
          }
          section.forms = formsWithConfig
        }
      }
    }
  } catch (error) {
    console.error('获取项目配置失败:', error)
    sections.value = []
  } finally {
    loading.value = false
  }
  
  updateTemplate()
}

// 章节选择操作
const selectAllSections = () => {
  selectedSections.value = sections.value.map(s => s._id)
  // 自动选择所有章节的所有表单
  sections.value.forEach(section => {
    if (section.forms?.length > 0) {
      selectedForms.value[section._id] = section.forms.map(f => f._id)
    }
  })
  updateTemplate()
}

const clearAllSections = () => {
  selectedSections.value = []
  selectedForms.value = {}
  updateTemplate()
}

// 表单选择操作
const getSelectedForms = (sectionId) => {
  return selectedForms.value[sectionId] || []
}

const updateSelectedForms = (sectionId, formIds) => {
  selectedForms.value[sectionId] = formIds
  updateTemplate()
}

const selectAllForms = (sectionId) => {
  const section = sections.value.find(s => s._id === sectionId)
  if (section?.forms) {
    selectedForms.value[sectionId] = section.forms.map(f => f._id)
    updateTemplate()
  }
}

const clearAllForms = (sectionId) => {
  selectedForms.value[sectionId] = []
  updateTemplate()
}

const getTotalSelectedForms = () => {
  return Object.values(selectedForms.value).reduce((total, forms) => total + forms.length, 0)
}

// 更新模板数据
const updateTemplate = () => {
  if (selectedSections.value.length === 0) {
    emit('update:modelValue', null)
    return
  }

  const selectedProject = projects.value.find(p => p._id === selectedProjectId.value)
  const template = {
    projectId: selectedProjectId.value,
    projectName: selectedProject?.name,
    sections: selectedSections.value.map(sectionId => {
      const section = sections.value.find(s => s._id === sectionId)
      return {
        ...section,
        forms: (section.forms || []).filter(form => 
          getSelectedForms(sectionId).includes(form._id)
        )
      }
    })
  }

  emit('update:modelValue', template)
}

// 监听章节选择变化，自动处理表单选择
watch(selectedSections, (newSections, oldSections) => {
  // 移除未选择章节的表单
  Object.keys(selectedForms.value).forEach(sectionId => {
    if (!newSections.includes(sectionId)) {
      delete selectedForms.value[sectionId]
    }
  })
  
  // 为新选择的章节自动选择所有表单
  newSections.forEach(sectionId => {
    if (!oldSections?.includes(sectionId)) {
      const section = sections.value.find(s => s._id === sectionId)
      if (section?.forms?.length > 0) {
        selectedForms.value[sectionId] = section.forms.map(f => f._id)
      }
    }
  })
})

onMounted(() => {
  getProjects()
})

// 监听导入来源变化（项目/模板），切换时重载列表并重置已选
watch(
  () => props.filterIsTemplate,
  () => {
    selectedProjectId.value = ''
    selectedSections.value = []
    selectedForms.value = {}
    emit('update:modelValue', null)
    getProjects()
  }
)
</script>

<style scoped>
.template-selector {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.template-header {
  margin-bottom: 20px;
}

.template-header h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.template-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.template-content {
  margin-bottom: 20px;
}

.project-section, .sections-section {
  margin-bottom: 24px;
}

.project-section h4, .sections-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
}

.section-list {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  background: #fafafa;
}

.loading, .empty {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.select-all-actions {
  margin-bottom: 12px;
  display: flex;
  gap: 8px;
}

.section-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.section-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  background: white;
}

.section-checkbox {
  width: 100%;
}

.section-info {
  flex: 1;
}

.section-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.section-desc {
  color: #606266;
  font-size: 14px;
  margin-bottom: 4px;
}

.section-stats {
  color: #909399;
  font-size: 12px;
}

.forms-section {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

.forms-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.form-actions {
  display: flex;
  gap: 8px;
}

.form-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-checkbox {
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #f9f9f9;
}

.form-info {
  flex: 1;
}

.form-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.form-code {
  color: #606266;
  font-size: 12px;
  margin-bottom: 2px;
}

.form-stats {
  color: #909399;
  font-size: 11px;
}

.selection-summary {
  margin-top: 20px;
}
</style> 